$(()=>{
    findAllMovie(1,20);
    // console.log("电影列表查询")
    $(".paginate").on("click", "li>a", function (e) {
        e.preventDefault();//停止向上冒泡

        let $a = $(this)
        let $li = $a.parent();
        if ($li.is(".first")) {//首页
            findAllMovie(1, 20, params);
        } else if ($li.is(".last")) {//尾页
            findAllMovie(pages, 20, params);
            //知道一共多少页
        } else if ($li.is(".prev")) {//上一页
            //获取当前页码
            let p = currentPage - 1;
            if (p < 1) {
                p = 1;
            }
            findAllMovie(p, 20, params)
        } else if ($li.is(".next")) {//下一页
            //获取当前页码
            let p = currentPage + 1;
            if (p > pages) {
                p = pages;
            }
            findAllMovie(p, 20)
        } else {//其他页码
            findAllMovie(parseInt($a.text()), 20, params);
        }
    });

    $("#check-all").click(function () {
        let checked = $(this).prop("checked");
        $("#tbl tr>td:first-child>:checkbox").prop("checked", checked);
    });
    //绑定清空
    $("#reset").click(function () {
        $("#search-form")[0].reset();
        findAllMovie(1,20);

    });
    //点击行选中 选中的是td
    $("#tbl").on("click", "tr>td:not(:first-child)", function () {
        //找到父元素
        let $tr = $(this).parent();
        //找到复选框 所有的td 第一个 孩子 复选框
        const $chk = $tr.children().first().children();
        const checked = $chk.prop("checked");
        $chk.prop("checked", !checked);
    });
    //查询按钮事件
    $("#search").click(function () {
        let name = $("#name").val();
        let startTime = $("#laydate-start-date").val();
        let endTime = $("#laydate-end-date").val();
        let actor = $("#actor").val();
        let rating = $("#rating").val();
        let movieTime = $("#movieTime").val();
        params = {
            name,
            startTime,
            endTime,
            actor,
            rating,
            movieTime
        }
        findAllMovie(1, 20, params);
    });
    //渲染日期选择器
    layui.use(() => {
        let laydate = layui.laydate;
        laydate.render({
            elem: "#range_date",
            range: ['#laydate-start-date', '#laydate-end-date'],
        });
    });
    $("#add").click(function () {
        layer.open({
            title: '新增电影',
            content: ctx + "/movie/add",
            type: 2,
            area: ["450px", "500px"],
            btn: ["确定", "取消"],
            offset: '100px',
            yes: function (handler, $jq) {
                const win = $jq.find("iframe")[0].contentWindow;
                win.submitAddMovie(function (success) {
                    if (success) {
                        layer.msg("成功")
                        findAllMovie();
                        layer.close(handler);
                    } else {
                        layer.msg("失败")
                    }
                });
            },

        })
    })
    $("#edit").click(function () {
        let $checked = $("#tbl tr>td:first-child>:checked");
        if ($checked.length === 0) {
            layer.msg("你TM的选了吗？")
        } else if ($checked.length > 1) {
            layer.msg("只能选一个电影")
        } else {
            let i = $checked.attr("data-id")

            layer.open({
                title: '修改电影',
                content: ctx + "/movie/edit?id=" + i,  //
                type: 2,
                area: ["450px", "500px"],
                btn: ["确定", "取消"],
                offset: '100px',
                yes: function (handler, $jq) {
                    const win = $jq.find("iframe")[0].contentWindow;
                    if (win && typeof win.submitEditMovie === 'function') {
                        win.submitEditMovie(function (success) {
                            if (success) {
                                layer.msg("修改成功");
                                findAllMovie();  // 刷新列表
                                layer.close(handler);
                            } else {
                                layer.msg("修改失败");
                            }
                        });
                    } else {
                        layer.msg("无法调用编辑方法");
                    }

                },

            })
        }
    })
    $("#del").click(function () {
        let $checked = $    ("#tbl tr>td:first-child>:checked");
        if ($checked.length === 0) {
            layer.msg("请选择要删除的记录");
        } else {
            layer.confirm("确定要删除这个吗,老登?", {
                offset: '200px',  // 距离顶部的距离
            }, function (handler) {
                // console.log("开始删除...")
                //删除所有选中的行
                let ids = [];
                $checked.each(function () {
                    ids.push(parseInt($(this).attr("data-id")));
                })
                // console.log(ids);
                deleteMovieByIds(ids, function (count) {
                    if (count > 0) {
                        layer.msg("删除成功,删除了" + count + "行");
                    } else {
                        layer.msg("删除失败");
                    }
                })
                layer.close(handler)
            }, function () {
                console.log("取消删除...")
            })
        }
    })
    $("#desc").click(function (){
        params.order = "desc";
        findAllMovie(1, 20, params);
    })
    $("#asc").click(function (){
        params.order = "asc";
        findAllMovie(1, 20, params);
    })

})
function findAllMovie(page=1,limit=20,params){
    console.log("开始请电影数据...");
    $.ajax({
        url:ctx +"/movie/list",
        method: "POST",
        data:{
            "page":page,//当前的页数
            "limit":limit,//每页多少数据
            ...params
        },
        dataType: "json",
        timeout: 10000, // 设置超时时间
        success: function (data){
            // console.log(data)数据
            let row = data.movieList;
            let pi=data.pi;
            currentPage = pi.pageNo;
            pages = pi.pages;
            // console.log(row)
            $("#tbl>tbody").empty();
            console.log(currentPage,pages)
            for(let i=0;i<row.length;i++){
                let movie = row[i];
                let $tr = $("<tr></tr>");
                $tr.append($("<td></td>").append($("<input>").attr("type", "checkbox").addClass("check-item").attr("data-id", movie.id)));
                $tr.append($("<td></td>").text(movie.id));
                let highlightName = "";
                if (params && params.name) {
                    highlightName = hightText(movie.name, params.name);
                } else {
                    highlightName = movie.name;
                }
                $tr.append($("<td></td>").html(highlightName));
                $tr.append($("<td></td>").text(movie.actor));
                $tr.append($("<td></td>").text(movie.dateTime));
                $tr.append($("<td></td>").text(movie.movieTime));
                $tr.append($("<td></td>").text(movie.rating));
                $tr.append($("<td></td>").text(movie.money));
                $("#tbl>tbody").append($tr);
            }

            //对于分页导航栏的逻辑 --- 计算分页
            const navPages=5;
            let startPage = page - Math.floor(navPages/2);
            if(startPage<1){
                startPage=1;
            }
            let end=startPage+navPages-1;
            if(end>pages){
                end=pages;
                startPage = end - navPages + 1;
                if (startPage < 1) {
                    startPage = 1;
                }
            }
            $(".paginate li:not(.first,.last,.prev,.next)").remove();
            for (let i = startPage; i <= end; i++) {
                let $li = $("<li>");
                $li.append($("<a></a>").text(i))
                // console.log("分页导航:",i)
                $(".paginate .next").before($li);
            }
            $("#total-all").text(pi.total)
            $("#total-pages").text(pages)
            $("#total-money").text(pi.totalMoney)
        }

    })
}
function deleteMovieByIds(ids, cb = $.noop) {
    //发送请求
    $.ajax({
        url: ctx + "/movie/delete",
        method: "POST",
        data: {
            "ids": ids
        },
        traditional: true,
        dataType: "json",
        success: function (data) {
            console.log("删除结果:", data);
            if (data.row === 0) {
                console.log(data);
                layer.msg("删除失败");
            } else {
                layer.msg("删除成功");
                cb(data.rows);
                findAllMovie(currentPage, 20);
            }
        }
    })
}
function hightText(oldText,newText){
    if (newText==null)return oldText;
    const regex=new RegExp(`(${newText})`,"gi");
    return oldText.replace(regex,"<span class='highlight'>$1</span>")

}